import React from 'react';
import PropTypes from 'prop-types';
import WPT from 'wpt';

import { throttle } from 'modules/RX';

const Link = ({
    href,
    to,
    curUrl,
    runFun,
    style,
    animation,
    children,
    noRecordHistory,
    enforceR = false,
    isInner = false,
    ...otherProps
}) => {
    const handleClick = throttle((e) => {
        e.preventDefault();
        const url = href || (curUrl && to && to.pathName);
        // 如果不是当前域名下的链接，直接跳转
        if (WPT.Util.urlParse(url).hostname !== window.location.hostname) {
            window.location.href = url;
            return;
        }
        if (url) {
            runFun && runFun();
            WPT.showPage(url, {
                enforceR,
                noAnimation: !animation,
                noRecordHistory,
            });
        }
    }, 1000);

    const link = href || (to && to.pathName) ? { 'data-link': href || to.pathName } : {};
    const newProps = {
        ...otherProps,
        ...link,
    };

    // 修复a标签下放置a标签报的警告
    if (isInner) {
        return (
            <div style={style} onClick={handleClick}>
                {children}
            </div>
        );
    }

    return (
        // eslint-disable-next-line no-script-url
        <a href="#!" style={style} {...newProps} {...WPT.onTouchEnd(handleClick)}>
            {children}
        </a>
    );
};

Link.propTypes = {
    href: PropTypes.string,
    // 旧页面写法
    to: PropTypes.shape({
        pathName: PropTypes.string,
    }),
    // 旧页面写法
    curUrl: PropTypes.string,
    // 页面切换前调用
    runFun: PropTypes.func,
    // 页面切换是否需要动画, 默认 true
    animation: PropTypes.bool,
    // 是否记录历史
    noRecordHistory: PropTypes.bool,
    children: PropTypes.node,
    // r强制替换
    enforceR: PropTypes.bool,
    isInner: PropTypes.bool,
    style: PropTypes.object,
};

Link.defaultProps = {
    href: '',
    to: {},
    curUrl: '',
    runFun: () => {},
    style: {},
    animation: true,
    children: null,
    enforceR: false,
    isInner: false,
    noRecordHistory: false,
};

export default Link;
